import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import axios from "axios";
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}
/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.url ? item.url : item.menuId + '_key',
      name: item.name,
      component: item.type === 0 ? Layout : (resolve) => require([`@/views${item.component}.vue`], resolve),
      hidden: item.type === 3,
      meta: {
        title: item.name,
        id: item.icon
      },
      children: []

    }
    if (item.sysMenuList) {
      generaMenu(menu.children, item.sysMenuList)
    }
    routes.push(menu)
  })
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      axios.get('http://localhost:9999/system-management/system/sysMenu/getMenus', {
        params: {
          username: localStorage.getItem('username'),
          access_token: localStorage.getItem('access_token')
        }
      }).then((res) => {
        // 获取后台路由资源
        Object.assign(loadMenuData, res.data.obj)
        generaMenu(asyncRoutes, loadMenuData)
        let accessedRoutes
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })

     /* var username = localStorage.getItem("username")
      getAuthMenu(state.token, username).then(response => {
        let data = response
        console.log(data + '----------------------------------------------------------')
        if (response.code !== 0) {
          this.$message({
            message: '菜单数据加载异常',
            type: 0
          })
        } else {
          data = response.data.sysMenuList
          Object.assign(loadMenuData, data)
        }
      })*/
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
